<?php
namespace api\zmt\controller;

use api\validate\Addressvalidate;
use api\validate\Uservalidate;
use api\zmt\model\AddressModel;
use api\zmt\model\LoginModel;
use api\zmt\model\SignModel;
use api\zmt\model\UsertableModel;
use cmf\controller\BaseController;
use cmf\controller\RestBaseController;
use think\facade\Db;
use think\facade\Filesystem;
use think\facade\Request;


class UserController extends  RestBaseController
{
    //注册
    public  function  register()
    {
        $data =input('post.');
        $validate = new Uservalidate();
        $result = $validate->scene('register');
        if(!$result){
            echo $validate->getError();
        }
        $user = \api\zmt\model\UsertableModel::where('mobile',$data['mobile'])->find();
        if($user){
            return error('该手机号已被注册') ;
        }

        $check = checkSmsCode($data['mobile'],$data['code']);
        if(!$check){
            return error('验证码错误');
        }

        $data['create_time'] = time();
        if(\api\zmt\model\UsertableModel::create($data)){
            return success('注册成功');
        }else{
            return error('注册失败');
        }
    }
    //登录
    public function login(){
        $data = input('post.');
        $validate = new Uservalidate();
        $result = $validate->scene('login')->check($data);
        if(!$result){
            return error($validate->getError());
        }
        $user = \api\zmt\model\UsertableModel::where('mobile',$data['mobile'])->find();
        if(!$user){
            return error('该账号不存在');
        }

        $check = checkSmsCode($data['mobile'],$data['code']);
        if(!$check){
            return error('验证码错误');
        }
        return success('登录成功');
    }
    public  function  yzm()
    {
        $data = input('post.');
        sendSms($data['mobile']);
    }

    //输出个人信息
    public function getUserList()
    {
        //第几页
        $page = input('page/d',1);
        //每页数据
        $pageSize = input('page_size/d',10);
        //排序
        $orderList = input('order_list/s','id');
        $orderType = input('order_type/s','DESC');

        $list = UsertableModel::order($orderList,$orderType)
            ->page($page,$pageSize)
            ->select();
        return success('查询成功',$list);
    }

    //添加图片
    public function addImage()
    {
        $mobile = input('mobile');
        $image = request()->file('image');
        $result = Filesystem::disk('public')->putFile('image',$image);

        if(!$mobile){
            return error('请输入手机号');
        }

        $image2 =   request()->domain().DIRECTORY_SEPARATOR.'storage'.DIRECTORY_SEPARATOR.$result;
        $addImage = UsertableModel::where('mobile','=',$mobile)->find();
        if (!$addImage){
            $this->error('未查询到数据');
        }

        $addImage->image = $image2;

        if ($addImage->save()){
            return json(['code' => 1,
                'msg' => "上传成功" ,
                'data' => [
                    'url' => $image2,
                ]
            ]);
        }else{
            return json(['code' => 0,'msg' => "上传失败" , 'data' => null]);
        }

    }

    public function editUser()
    {
        $data = input('post.');
        halt($data);
        //判断器
        $validate = new Uservalidate();
        $result = $validate->scene('login')->check($data);
        //判断手机号是否相同
        $existMobile = UsertableModel::where('mobile','=',$data['mobile'])->find();
        if ($existMobile){
            return error('手机号存在相同');
        }
        //去除image数据
        unset($data['image']);
        //修改图片
        $image = request()->file('image');
        $result = Filesystem::disk('public')->putFile('image',$image);
        $image2 =   request()->domain().DIRECTORY_SEPARATOR.'storage'.DIRECTORY_SEPARATOR.$result;

        //修改数据库
        $edit = UsertableModel::where('id','=',$data['id'])->find();
        if (!$edit){
            $this->error('未查询到数据');
        }

        $edit->mobile = $data['mobile'];
        $edit->image = $image2;
        $edit->account_type = $data['account_type'];
        $edit->status = $data['status'];
        $edit->user_name = $data['user_name'];
        if ($edit->save()){
            return success('修改成功');
        }else{
            return error('修改失败');
        }
    }

    //七牛
    public function qiniu()
    {
        $accessKey = config('app.qiniu.accessKey');
        $secretKey = config('app.qiniu.secretKey');
        $bucket = config('app.qiniu.bucket');
    }
    //更新信息
    public function UpdateAdmin(Request $request)
    {
        $token = $request->header();
        if(!isset($token['token']) || empty($token['token']))
        {
            $this->error('缺少token');
        }
        $key = new Key(config('app.jwt_key'),'HS256');

        try {
            $res = JWT::decode($token['token'],$key);
        }catch (\Exception $exception){
            $this->error($exception->getMessage());
        }
        $user_name = $request->param('user_name');
        $mobile = $request->param('mobile');
        $image = $request->param('image');
        $res = LoginModel::where('id','=',$res->data->user_id)
            ->update([
                'user_image'=>$image,
                'name'=>$user_name,
                'mobile'=>$mobile
            ]);
        if(!empty($res))
        {
            $this->success('修改成功');
        }else{
            $this->error('修改失败');
        }
    }
    //查看收货地址
    public function address(Request $request)
    {
        $user_id = $request->user_id;
        $page = input('page/d',1);
        $pageSize = input('page_size/d',10);
        $list = AddressModel::field('mobile,address_user,address,complete_address')
            ->order('id','desc')
            ->where('user_id','=',$user_id)
            ->page($page,$pageSize)
            ->select();

        $this->success('收货信息列表',$list);
    }
    //添加收货地址
    public function AddAddress(Request $request)
    {
        $user_id = $request->user_id;
        $data = input();
        //验证数据
        $validate = new Addressvalidate();
        $result = $validate->scene('add')->check($data);
        if(!$result){
            $this->error($validate->getError());
        }
        $data['create_time'] = date('Y:m:d H:i:s');
        $data['user_id'] = $user_id;
        $add = AddressModel::create($data);
        if($add){
            $this->success('添加成功');
        }
        $this->error('添加失败');
    }
    //修改收货地址
    public function updateAddress(Request $request)
    {
        $user_id = $request->user_id;
        $data = input();
        //验证数据
        $validate = new AddressValidate();
        $result = $validate->scene('edit')->check($data);
        if(!$result){
            $this->error($validate->getError());
        }
        $data['update_time'] = date('Y:m:d H:i:s');
        $edit = AddressModel::where('user_id','=',$user_id)
            ->update($data);
        if($edit){
            $this->success('修改成功');
        }
        $this->error('修改失败');
    }
    //签到
    public function sign(Request $request)
    {
        $user_id = $request->user_id;
        if(!$user_id)
        {
            $this->error('签到失败');
        }
        $res = SignModel::create([
            'user_id'=>$user_id,
            'status'=>1,
            'create_time'=>date('Y:m:d H:i:s')
        ]);
        if($res)
        {
            $this->success('签到成功');
        }
    }
    public function money(Request $request)
    {
        $money = $request->param('money');
        if(!$money)
        {
            $this->error('请输入金额');
        }
        $user = LoginModel::find($request->user_id);
        if(!$user)
        {
            $this->error('参数错误');
        }
        $after = $user['wallet'] + $money;
        // 启动事务
        Db::startTrans();
        try {
            $res = money_log($request->user_id,$money,$user['wallet'],$after,'1');
            $log = LoginModel::where('id','=',$request->user_id)->update(['wallet'=>$after]);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
        }
        if ($res && $log) {
            // 提交事务
            Db::commit();
            $this->success('充值成功');
        } else {
            // 回滚事务
            Db::rollback();
            $this->error('充值成功');
        }

    }
}
}